package org.zsk.cs.algorithnm.loadbalance.sendorder.impl;

import org.zsk.cs.algorithnm.entity.EmployTask;
import org.zsk.cs.algorithnm.loadbalance.sendorder.LoadBalance;
import org.zsk.cs.algorithnm.loadbalance.sendorder.SendOrderUtil;

import java.util.List;

/**
 * 负载均衡-最少连接派单
 * @author zsk
 * 2021/4/19 下午8:11
 */
public class LeastLoadBalancer implements LoadBalance<EmployTask> {

    @Override
    public EmployTask pickOne() {
        List<EmployTask> availableEmployTasksInList = SendOrderUtil.getAvailableEmployTasksInList();
        EmployTask employTask1 = availableEmployTasksInList.stream().reduce((employTask, employTask2) -> {
            if (employTask.getTotalNumOfTask() <= employTask2.getTotalNumOfTask()) {
                return employTask;
            }
            return employTask2;
        }).orElseThrow(()->new RuntimeException("找不到最少任务的员工"));
        employTask1.setTotalNumOfTask(employTask1.getTotalNumOfTask()+1);
        employTask1.setActiveNumOfTask(employTask1.getActiveNumOfTask()+1);
        return employTask1;
    }

    public static void main(String[] args) {
        LeastLoadBalancer leastLoadBalancer = new LeastLoadBalancer();
        for (int i = 0; i < 20; i++) {
            System.out.println(leastLoadBalancer.pickOne().toString());
        }
    }

}
